// 需要linux系统安装ffmpeg和yasm


const router = require('koa-router')();
const multer = require('koa-multer');
const path = require('path');
const fs = require('fs');
const exec = require('child_process').exec;
const speech = require('../tools/script/speech');
const axios = require('axios')
const qs = require('qs')
const md5 = require('md5')
const request = require('request')
const CircularJSON = require('circular-json');
const {
  mysql
} = require('../qcloud')

require('pinyin4js') //获取拼音

// sh命令文件路径
const shPath = '../../temp/audio/'
//存储文件至path.resolve('./voice-file')路径
var upload = multer({
  dest: path.resolve(shPath)
});


let dt = new Date();
let yy = dt.getFullYear(),
  mm = (dt.getMonth() + 1).toString().padStart(2, 0),
  dd = (dt.getDate()).toString().padStart(2, 0)
let dateLine = `${yy}-${mm}-${dd}`

/**
 * 上传录音文件
 */
router.post('/', upload.single('file'), async function (ctx, next) {

  // console.log(ctx.req.file);
  const token = ctx.req.body.token
  if (ctx.req.body.lang == 'cn') {
    await mysql('counter')
      .where('dict_date', dateLine)
      .increment('cnAsr_count', 1)

    let res = await silkToWav(path.resolve(shPath + ctx.req.file.filename))
    // console.log(res);
    if (res.result) {
      // console.log('文件转换wav成功');
      var filePath = path.resolve(shPath + ctx.req.file.filename + '.wav');
      // console.log(filePath);
      var base64Data = await speech.base64_encode(filePath);
      // console.log(base64Data);
      var fileInfo = await speech.fileStat(filePath);
      // console.log(fileInfo);
      var recogniz = await speech.recognize(base64Data.msg, fileInfo.msg.size, token);
      let voiceTxt = (CircularJSON.parse(recogniz.msg)).result;
      [voiceTxt] = [...voiceTxt];
      // console.log(voiceTxt);
      let uyTxt = await axios.post('https://wx.2xur7.cn/weapp/dict', {
        txt: voiceTxt,
        from: 'zh'
      }).then(res => {
        return res.data.data.res_txt
      })
      let pinyin = PinyinHelper.convertToPinyinString(voiceTxt, ' ', PinyinFormat.WITH_TONE_MARK)
      // msg: recogniz.msg,
      let result = {
        code: 200,
        voiceTxt,
        pinyin,
        uyTxt
      };
      ctx.response.body = result;
      // console.log(recogniz);
    }
  } else if (ctx.req.body.lang == 'uy') {
    await mysql('counter')
      .where('dict_date', dateLine)
      .increment('uyAsr_count', 1)
    let res = await silkToWav(path.resolve(shPath + ctx.req.file.filename))
    if (res.result) {
      var filePath = path.resolve(shPath + ctx.req.file.filename + '.wav');
      // console.log(filePath)
      let voiceRes = await uyAsr(filePath)
      voiceRes = CircularJSON.parse(voiceRes)
      let result = voiceRes.ResponseInfo.Result.Text;
      // console.log('这是结果', result);

      let dictRes = await axios.post('https://wx.2xur7.cn/weapp/dict', {
        txt: result,
        from: "uy"
      }).then(res => {
        return res.data.data
      })
      let resBody = {
        uyTxt: result,
        cnTxt: dictRes.res_txt,
        pin: dictRes.pin
      }
      ctx.response.body = {
        resBody
      };
    }

  } else {
    console.log('文件转换wav失败: ' + CircularJSON.stringify(res.msg));
    result = {
      code: 88,
      msg: '文件转换wav失败: '
    };
  }


});


function rename(oldPath, newPath) {

  return new Promise(function (resolve, reject) {
    fs.rename(oldPath, newPath, function (err) {
      if (err) {
        console.error(err);
        resolve({
          result: false,
          msg: err
        });
      }
      resolve({
        result: true,
        msg: ''
      });
    });
  });
}

function silkToWav(file) {
  console.log('这是地址file:' + file);
  return new Promise(function (resolve, reject) {
    exec('sh /www/wwwroot/temp/converter.sh ' + file + ' wav', function (err, stdout, stderr) {
      if (err) {
        console.log(err);
        resolve({
          result: false,
          msg: stderr
        });
      } else {
        //var data = JSON.parse(stdout);
        console.log('转换成功' + stdout);
        // console.log('stderr' + stderr);
        //console.log(err);
        resolve({
          result: true,
          msg: ''
        });
      }
    });
  });
}

function exists(file) {
  return new Promise(function (resolve, reject) {
    fs.exists(file, function (exists) {
      resolve(exists)
    });
  });
}

function uyAsr(path) {
  let date = new Date().toLocaleString().replace(/\//g, '-').replace(/[\u4e00-\u9fa5]/g, '');
  return new Promise((resolve, reject) => {
    request.post({
      url: 'http://api.hcicloud.com:8880/asr/recognise',
      headers: {
        'x-app-key': '345d54aa',
        'x-sdk-version': '5.0',
        'x-request-date': date,
        'x-task-config': 'capkey=asr.cloud.freetalk.uyghur, audioformat=pcm16k16bit',
        'x-session-key': md5(date + '4fc224832ecc57967bec02e89aa5a065'),
        'x-result-format': 'json',
        'x-udid': "101:1234567890"
      },
      formData: {
        buffer: {
          value: fs.readFileSync(path),
          options: {
            filename: '111.wav',
            contentType: 'audio/wav'
          }
        }
      },
    }, function optionalCallback(err, httpResponse, body) {
      if (err) {
        reject(err)
        // return console.error('upload failed:', err);
      } else {
        resolve(body)
      }
      // console.log('Upload successful!  Server responded with:', body);
      // return body
    });
  })
}
module.exports = router;
